package cc.ccoke.validate.factory;

import cc.ccoke.validate.entity.Regular;
import cc.ccoke.validate.exception.ParamException;

import java.util.*;

/**
 * 一些默认规则以及整合自定义规则
 * @author ccoke
 */
public class RegularFactory {
    public static Map<String, Regular> DEFAULT_REGULARS;

    static {
        DEFAULT_REGULARS = new HashMap<>();
        DEFAULT_REGULARS.put("EMAIL", new Regular("[\\w!#$%&'*+/=?^_`{|}~-]+(?:\\.[\\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\\w](?:[\\w-]*[\\w])?\\.)+[\\w](?:[\\w-]*[\\w])?", "邮箱"));
        DEFAULT_REGULARS.put("URL", new Regular("[a-zA-z]+://[^\\s]*", "链接"));
        DEFAULT_REGULARS.put("QQ", new Regular("[1-9][0-9]{4,}", "QQ"));
        DEFAULT_REGULARS.put("POSTAL_CODE", new Regular("[1-9]\\d{5}(?!\\d)", "邮编应为6位数字"));
        DEFAULT_REGULARS.put("ID_NUMBER", new Regular("^(\\d{6})(\\d{4})(\\d{2})(\\d{2})(\\d{3})([0-9]|X)$", "身份证号(18位，前17位必须为数字，最后一位可以是大写的X)"));
    }

    public static void setRegulars(List<Regular> regulars){
        if (regulars == null || regulars.size() == 0){
            return;
        }
        for (int i = 0; i < regulars.size(); i++) {
            Regular regular = regulars.get(i);
            if (regular.getName() == null || "".equals(regular.getName().trim())) {
                throw new ParamException("从配置文件读取规则出错，错误在第" + (i + 1) + "行");
            }
            if (regular.getRegex() == null || "".equals(regular.getRegex().trim())) {
                throw new ParamException("从配置文件读取规则出错，规则:" + regular.getName() + " 的正则不能为空");
            }
            DEFAULT_REGULARS.put(regular.getName(), regular);
        }
    }

}
